package com.jjc.android.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import com.allen.library.SuperButton
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.hjq.toast.ToastUtils
import com.jjc.android.Constants
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.BottomWheelDialog
import com.jjc.android.dialog.MessageImageDialog
import com.jjc.android.entity.*
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.AndroidBug5497Workaround
import com.jjc.android.util.GlobalActivityStack
import com.jjc.android.util.InputFilterMinMax
import com.jjc.android.util.messenger.ActivityMessenger
import com.jjc.android.util.paramEx
import com.jjc.android.view.CommonKt.genderParse
import com.jjc.android.view.formatTwo
import com.jjc.android.view.onClick
import com.jjc.android.view.textChange
import com.lzy.okgo.OkGo
import com.xw.repo.XEditText
import org.greenrobot.eventbus.EventBus

class AddTestedPersonActivity : BaseActivity(){

    companion object{

        fun start(context: Activity,person:TestedPersonDto? = null,action:((String?)->Unit)? = null){
            val intent = Intent(context,AddTestedPersonActivity::class.java)
            if(person!=null){
                intent.putExtra(Constants.BUNDLE_INFO,person)
            }
            ActivityMessenger.startActivityForResult(context,intent){
                (it?.getStringExtra(Constants.BUNDLE_INFO)).let{
                    action?.invoke(it)
                }
            }
        }
    }

    override val layoutId: Int = R.layout.activity_add_tested_person

    private val okBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.okBtn) }
    private val weightEt: XEditText by lazy { findViewById<XEditText>(R.id.weightEt) }
    private val tallEt: XEditText by lazy { findViewById<XEditText>(R.id.tallEt) }
    private val chooseBirthDayBtn: TextView by lazy { findViewById<TextView>(R.id.chooseBirthDayBtn) }
    private val chooseGenderBtn: TextView by lazy { findViewById<TextView>(R.id.chooseGenderBtn) }
    private val nameEt: XEditText by lazy { findViewById(R.id.nameEt) }
    private var editTestedPersonDto:TestedPersonDto? = null

    override fun initView(savedInstanceState: Bundle?) {
        AndroidBug5497Workaround.assistActivity(this)
        if(editTestedPersonDto==null){
            setActivityTitle(getString(R.string.create_tester_txt))
        }else{
            setActivityTitle(getString(R.string.edit_tester_txt))
        }
        chooseGenderBtn.onClick {
            genderDialog.show()
        }
        chooseBirthDayBtn.onClick {
            birthdayPicker.show()
        }
        tallEt.filters = arrayOf(InputFilterMinMax(0f,250f))
        weightEt.filters = arrayOf(InputFilterMinMax(0f,400f))
        okBtn.onClick {
            if(nameEt.textEx.isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_name_txt))
                return@onClick
            }
            if(chooseGenderBtn.text.isNullOrEmpty()){
                ToastUtils.show(getString(R.string.choose_gender))
                return@onClick
            }
            if(chooseBirthDayBtn.text.isNullOrEmpty()){
                ToastUtils.show(getString(R.string.choose_birth_txt))
                return@onClick
            }
            if(tallEt.textEx.isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_tall_txt))
                return@onClick
            }
            if(weightEt.textEx.isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_weight_fx_txt))
                return@onClick
            }
            checkUserName(nameEt.textEx){
                submit()
            }
        }

        editTestedPersonDto?.let { person->
            nameEt.setText(person.jsonMember8pa55qzbspju5tzn)
            chooseGenderBtn.text = person.kpurkwtmvsd9lqui.genderParse(false)
            chooseBirthDayBtn.text = person.orldw605kccdju8z.let { if(it.isNullOrEmpty()) "" else if(it.length>10) it.substring(0,10) else it }
            tallEt.setText(person.cu8thtdjxhfbxpjx)
            weightEt.setText(person.yzqfbls6zzqh9tyl)
        }
    }

    private fun submit(){
        if(editTestedPersonDto==null){
            OkGo.post<LzyResponse<IdValuePair>>(Constants.addFormRow)
                .paramEx(mutableMapOf(
                    "formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b",
                    "fields" to mapOf<String,Any?>("61xugqtzoyid5pw2" to UserManager.userId(),
                        "8pa55qzbspju5tzn" to nameEt.textEx,
                        "cu8thtdjxhfbxpjx" to tallEt.textEx,
                        "kpurkwtmvsd9lqui" to chooseGenderBtn.text.toString().genderParse(true),
                        "orldw605kccdju8z" to chooseBirthDayBtn.text.toString(),
                        "yzqfbls6zzqh9tyl" to weightEt.textEx)
                ),true)
                .tag(this@AddTestedPersonActivity)
                .execute(object : SimpleHttpCallback<LzyResponse<IdValuePair>>(){
                    override fun onCallSuccess(response: LzyResponse<IdValuePair>) {
                        hideLoadingDialog()
                        EventBus.getDefault().post(ChangeTesterEvent())
                        ToastUtils.show(response.msg.let { if(it.isNullOrEmpty()) getString(R.string.create_tester_success_txt) else it })
                        setResult(Activity.RESULT_OK,Intent().apply {
                            putExtra(Constants.BUNDLE_INFO,response.data.id)
                        })
                        finish()
                    }

                    override fun onCallError(error: String?) {
                        super.onCallError(error)
                        hideLoadingDialog()
                    }
                })
        }else{
            OkGo.post<LzyResponse<Any>>(Constants.editFormRowById)
                .paramEx(mutableMapOf(
                    "formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b",
                    "rowid" to editTestedPersonDto?.id,
                    "fields" to mapOf<String,Any?>(
                        "8pa55qzbspju5tzn" to nameEt.textEx,
                        "cu8thtdjxhfbxpjx" to tallEt.textEx,
                        "kpurkwtmvsd9lqui" to chooseGenderBtn.text.toString().genderParse(true),
                        "orldw605kccdju8z" to chooseBirthDayBtn.text.toString(),
                        "yzqfbls6zzqh9tyl" to weightEt.textEx)
                ),true)
                .tag(this@AddTestedPersonActivity)
                .execute(object : SimpleHttpCallback<LzyResponse<Any>>(){
                    override fun onCallSuccess(response: LzyResponse<Any>) {
                        hideLoadingDialog()
                        EventBus.getDefault().post(ChangeTesterEvent())
                        ToastUtils.show(response.msg.let { if(it.isNullOrEmpty()) getString(R.string.edit_tester_success_txt) else it })
                        setResult(Activity.RESULT_OK,Intent().apply {
                            putExtra(Constants.BUNDLE_INFO,editTestedPersonDto?.id)
                        })
                        finish()
                    }

                    override fun onCallError(error: String?) {
                        super.onCallError(error)
                        hideLoadingDialog()
                    }
                })
        }
    }

    private fun checkUserName(userName:String,action:()->Unit){
        showLoadingDialog()
        if(editTestedPersonDto!=null){
            action.invoke()
            return
        }
        OkGo.post<LzyResponse<PageInfo<TestedPersonDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf("needpage" to "0","formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b","filters" to listOf<KeyValuePair>(
                KeyValuePair("61xugqtzoyid5pw2",UserManager.userId()), KeyValuePair("8pa55qzbspju5tzn",userName)
            )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<TestedPersonDto>>>(false){
                override fun onCallSuccess(response: LzyResponse<PageInfo<TestedPersonDto>>) {
                    var isShowHintDialog = false
                    if(editTestedPersonDto==null && !response.data?.data.isNullOrEmpty()){
                        isShowHintDialog = true
                    }else if(editTestedPersonDto!=null && response.data?.data?.size.let { if(it!=null) it>1 else false }){
                        isShowHintDialog = true
                    }
                    if(isShowHintDialog){
                        hideLoadingDialog()
                        MessageImageDialog.Builder(this@AddTestedPersonActivity)
                            .imageResId(R.mipmap.alert_shibai_pic)
                            .title(getString(R.string.tips_txt))
                            .content(getString(R.string.same_tester_name_txt))
                            .cancleText(getString(R.string.cancle_txt))
                            .okText(getString(R.string.ok_txt))
                            .okClick {
                                action.invoke()
                            }
                            .build()
                            .show()
                    }else{
                        action.invoke()
                    }
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    action.invoke()
                }
            })
    }

    private val genderDialog by lazy {
        BottomWheelDialog<KeyValuePair>(this)
            .title(getString(R.string.choose_gender_txt))
            .contentList(listOf(
                KeyValuePair(Constants.Gender_Woman, getString(R.string.woman_txt)),
                KeyValuePair(Constants.Gender_Man, getString(R.string.man_txt))
            ))
            .onItemClick { position, value ->
                chooseGenderBtn.text = value.value
            }
            .build()
    }

    private val birthdayPicker: DatePicker by lazy {
        val picker = DatePicker(this)
        picker.wheelLayout.setRange(DateEntity.yearOnFuture(-100), DateEntity.today())
        picker.setOnDatePickedListener { year, month, day ->
            chooseBirthDayBtn.text = String.format("%d-%s-%s", year, month.formatTwo(), day.formatTwo())
        }
        picker
    }

    override fun setupArguments(args: Bundle?) {
        editTestedPersonDto = args?.getSerializable(Constants.BUNDLE_INFO) as? TestedPersonDto
    }

}